package com.maybach.core.shiro.realm;

import com.audi.dubbo.api.admin.models.AdminModel;
import com.maybach.core.dubbo.consumer.adapter.AdminServiceDubooAdapter;
import com.maybach.core.security.AdminUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * Created by houenxun on 16/1/12.
 */
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminServiceDubooAdapter adminServideDubooAdapter;

    /**
     * 权限验证
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        AdminModel adminModel = null;
        if (null != session) {
            adminModel = (AdminModel) session.getAttribute(AdminUser.ADMIN_MODEL_KEY);
            if (null == adminModel) {
                adminModel = adminServideDubooAdapter.getAdminModelByAdminId((Long) principals.getPrimaryPrincipal());
                if (null != adminModel) {
                    session.setAttribute(AdminUser.ADMIN_MODEL_KEY, adminModel);
                }
            }
        }
        SimpleAuthorizationInfo authorizationInfo = null;
        if (null != adminModel) {
            authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.setRoles(adminModel.getRoleMap().keySet());
            authorizationInfo.setStringPermissions(adminModel.getAuthMap().keySet());

        }
        return authorizationInfo;
    }

    /**
     * 登录验证
     *
     * @param token
     * @return
     * @throws org.apache.shiro.authc.AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        AdminModel adminModel = adminServideDubooAdapter.getAdminModelByLoginName((String) token.getPrincipal());
        if (null == adminModel) {
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute(AdminUser.ADMIN_MODEL_KEY, adminModel);
        return new SimpleAuthenticationInfo(adminModel.getAdminId(), adminModel.getPassword(), getName());
    }
}